Change the Minecraft world using Python

The Pyramid

This program links Python to Minecraft and uses that link to change things in the Minecraft world. In the game, move your player to an open area, then work your way through the blocks of code below.

First, we need to bring in some libraries of code that actually do the linking. Python does this with the import command.


In [ ]:
import mcpi.minecraft as minecraft
import mcpi.block as block
from time import sleep

Connect to the Minecraft server, store the connection in a variable named world:


In [ ]:
world  =  minecraft.Minecraft.create()

Next, set some variables to customize the pyramid. You might come back here later to change these values to build bigger pyramids, smaller pyramids, or ones made out of different stuff.


In [ ]:
height    =  5
material  =  block.COBBLESTONE

Find out where the player is in the world. Store the current position in variables named x, y, and z:


In [ ]:
[x,y,z] =  world.player.getPos()
[x, y, z]

Now, get busy building the pyramid.


In [ ]:
# This variable will track the current level being created inside the loop
level  =  1

# Execute the loop, building from the bottom up
while level <= height:
    print "Level " + str(level)  # Print the levels as we build them
    sleep(0.5)
    world.setBlocks( x - level, y + height - level, z - level,
                     x + level, y + height - level, z + level, material )
    level  =  level + 0.5

Finally, move the player to best seat in the house:


In [ ]:
# Put the player on top of the pyramid!
world.player.setPos( x, y + height, z )
world.postToChat("Done building pyramid!")

If you built a pyramid from TNT, now might be a good time to equip yourself with a flint and steel to make sparks fly!

Advanced Exercises and Questions

  1. What would you change to build a pyramid out of glass?
  2. How would you make a taller or shorter pyramid?
  3. Can you build a pyramid upside down? With the narrow end at the bottom and the wide end on top?
  4. Can you fill a pyramid with air? Hint: Maybe this is a two step process...